package net.xiangcaowuyu.example1.listener;

import lombok.extern.slf4j.Slf4j;
import net.xiangcaowuyu.example1.domain.SysUser;

import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;

/**
 * 博客：https://www.xiangcaowuyu.net
 * Description:
 *
 * @Author: 香草物语
 * DateTime: 2021-07-22 16:51
 */
@Slf4j
public class UserAuditListener {

    @PostPersist
    private void postPersist(SysUser sysUser) {
        recordLog(sysUser, OperateType.CREATE);
    }

    @PostRemove
    private void postRemove(SysUser sysUser) {
        recordLog(sysUser, OperateType.REMOVE);
    }

    @PostUpdate
    private void postUpdate(SysUser sysUser) {
        recordLog(sysUser, OperateType.UPDATE);
    }

    @PostLoad
    public void postLoad(SysUser sysUser) {
        recordLog(sysUser, OperateType.LOAD);
    }

    /**
     * 记录审计日志
     *
     * @param sysUser     用户实体
     * @param operateType 操作类型
     */
    private void recordLog(SysUser sysUser, OperateType operateType) {
        log.info("{}执行了{}操作", sysUser, operateType.getType());
    }

}

enum OperateType {

    CREATE("创建"), UPDATE("更新"), REMOVE("删除"), LOAD("查询");

    private final String type;

    OperateType(String type) {
        this.type = type;
    }

    public String getType() {
        return this.type;
    }
}
